package com.lbc.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 *   求和计算的任务
 *   3000    6000 (ForkJoin)   9000 (Stream并行流)
 *   //  1、forkjoinPool 通过它来执行
 *   //  2、计算任务 forkjoinPool.execute(ForkJoinTask)
 *   //  3、计算类要继承 ForkJoinTask
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private static long start;  // 1
    private static long end;    // 199090000

    //  临界值
    private static long temp = 10000L;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if ((end-start)<temp) {
            long sum = 0L;
            for (long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {  //  forkjoin 递归
            //  分支合并计算
            long middle = (start+end) / 2;
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(middle, end);
            task2.fork();  //  拆分任务，把任务压入线程队列

            return task1.join() + task2.join();
        }
    }

}
